<?php
/**
* 继承系统异常处理类，重新处理返回异常信息的格式
* create by ChenHuaiqi
*/

namespace app\lib\exception;

use think\Exception;
use think\exception\Handle;
use think\Request;
use think\Log;
use think\Config;
use app\lib\exception\BaseException;


class ExceptionHandler extends Handle
{
	private $code;
	private $msg;
	private $errorCode;

	public function render(\Exception $e){

		if($e instanceof BaseException){

			$this->code = $e->code;
			$this->msg = $e->msg;
			$this->errorCode = $e->errorCode;

		}else{

			if(Config::get('app_debug')){
				return parent::render($e);
			}else{

				$this->code = 500;
				$this->msg = '服务器错误';
				$this->errorCode = 999;

				$this->recordErrorLog($e);
			}
		}

		$request = Request::instance();

		$result = array(
			'msg'=>$this->msg,
			'error_code'=>$this->errorCode,
			'request_url'=>$request->url()
		);


		return json($result,$this->code);
	}

	private function recordErrorLog(\Exception $e){

		Log::init(array(
			'type'=>'file',
			'path'=>LOG_PATH,
			'error'=>['error']
		));

		Log::record($e->getMessage(),'error');

	}
}
